'''
Created on 2011-5-19

@author: elm
'''
from ddbms.SqlStatement import *
from functools import reduce
  
    
class RATree:
    'A base class for Relational Algebra Expression'
    executionSite = None
    
class Projection(RATree):
    input = None
    fields = None
    def __init__(self,input=None,fields=None):
        self.input=input
        self.fields=fields
    def __str__(self):
        return '(PROJECTION:[%s] %s)'%(','.join('%s'%f for f in self.fields),self.input)
        
class Select(RATree):
    input = None
    condition = None
    def __init__(self,input=None,condition=None):
        self.input=input
        self.condition=condition
    def __str__(self):
        return '(SELECT:%s %s)'%(self.condition,self.input)
        
class Join(RATree):
    segmentJoin = False
    lefttable = None
    righttable = None
    leftkey = None
    rightkey = None
    def __init__(self,lefttable=None,righttable=None,leftkey=None,rightkey=None):
        self.lefttable=lefttable
        self.righttable=righttable
        self.leftkey=leftkey
        self.rightkey=rightkey
    def __str__(self):
        if(self.leftkey.column==self.rightkey.column):
            return '(%s JOIN %s ON [%s])'%(self.lefttable,self.righttable,self.leftkey.column)
        else:
            return '(%s JOIN %s ON %s=%s)'%(self.lefttable,self.righttable,self.leftkey,self.rightkey)
    
class Union(RATree):
    segmentUnion = False
    lefttable = None
    righttable = None
    def __init__(self,lefttable=None,righttable=None):
        self.lefttable=lefttable
        self.righttable=righttable
        
    def __str__(self):
        return '(%s UNION %s)'%(self.lefttable,self.righttable)
    
class Product(RATree):
    'Cartesian Product'
    lefttable = None
    righttable = None
    def __init__(self,lefttable=None,righttable=None):
        self.lefttable=lefttable
        self.righttable=righttable
    def __str__(self):
        return '(%s * %s)'%(self.lefttable,self.righttable)
    
class RATable(RATree):
    'A table in logical database'
    name = None
    def __init__(self,name=None):
        self.name=name
    def __str__(self):
        return '[%s]'%self.name
    
class TableSegment(RATree):
    'A table segment in physical database'
    name = None
    index = 0
    condition = None
    id = 0
    def __init__(self,name=None,index=0,id=0,condition=None):
        self.name = name
        self.index = index
        self.condition = condition
        self.id = id
    def __str__(self):
        return '%s[%d]'%(self.name,self.index)

    
    
